package com.work.common.exp;

import com.work.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(WorkException.class)
    public Result<String> workException(WorkException e) {
        log.error("业务异常-->", e);
        return new Result<>(e.getCode(), e.getMsg());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数校验异常-->", e);
        final FieldError error = e.getBindingResult().getFieldError();
        return new Result<>(500, error != null ? error.getDefaultMessage() : "参数错误!");
    }

    @ExceptionHandler(Exception.class)
    public Result<String> exception(Exception e) {
        log.error("常规异常-->", e);
        return new Result<>(500, e.getMessage());
    }
}
